/**
 * 触发提现接口
 */

//引入Q模块
let Q = require('q');
//引入公共函数
let util = require('../../util');

let db, redis;

let index = function(getData, postData, config, _redis, _db) {
	let deferred = Q.defer();
	if(postData.withdrawCashOrderList && postData.withdrawCashTotal) {
		db = _db;
		redis = _redis;
		let withdrawCashOrderList = postData.withdrawCashOrderList || [];
		let orData = [];
		for(index in withdrawCashOrderList) {
			orData.push({orderId: withdrawCashOrderList[index]});
		}
		db.select('storeOrder', {$or: orData}).then(function(orderList) {
			if(withdrawCashOrderList.length == orderList.length) {
				let withdrawCashTotal = 0;
				for(let orderIndex in orderList) {
					if(orderList[orderIndex].storeReceiveMoney || orderList[orderIndex].withdrawCashId != '') {
						//提现的订单id中包含已提现或提现中的订单id
						deferred.reject('-0124');
						break;
					}
					for(let goodsIndex in orderList[orderIndex].goodsList) {
						withdrawCashTotal += orderList[orderIndex].goodsList[goodsIndex].foodPrice || orderList[orderIndex].goodsList[goodsIndex].goodsPrice;
					}
					//判断是否已经查找完毕通过验证
					if(orderIndex == orderList.length - 1) {
						createWithdrawCash(postData.storeId, postData._3rdSession, orData, withdrawCashOrderList, withdrawCashTotal).then(function(data) {
							deferred.resolve(data);
						}, function(errCode) {
							deferred.reject(errCode);
						});
					}
				}
			}
			else {
				//提现的订单数量和数据库中查询的订单数量不一致
				deferred.reject('-0123');
			}
		}, function() {
			//查找需要提现的订单失败
			deferred.reject('-0122');
		});
	}
	else {
		//触发提现接口的参数不足
		deferred.reject('-0121');
	}
	return deferred.promise;
}

let createWithdrawCash = function(storeId, _3rdSession, orData, withdrawCashOrderList, withdrawCashTotal) {
	let deferred = Q.defer();
	//生成32位的提现ID
	util.createRandomStr(32).then(function(withdrawCashId) {
		let userId = 'unknown';
		//根据3rdSession获取用户ID
		getUserId(_3rdSession).then(function(_userId) {
			userId = _userId;
			//修改所有要提现的订单的提现ID为刚刚生成的提现ID
			return db.updateAll('storeOrder', {
				userPayed: true,
				orderDone: true,
				$or: orData
			}, {
				withdrawCashId: withdrawCashId
			});
		}, function() {
			//获取用户ID失败
			deferred.reject('-0125');
		}).then(function() {
			return db.connectDB('common');
		}, function() {
			//设置提现订单的提现ID失败
			deferred.reject('-0126');
		}).then(function(commonDB) {
			console.log(commonDB);
			return commonDB.insert('withdrawCashLogs', {
				storeId: storeId,
				userId: userId,
				withdrawCashId: withdrawCashId,
				withdrawCashOrderList: withdrawCashOrderList,
				withdrawCashTotal: withdrawCashTotal,
				withdrawCashTimestamp: Date.now(),
				withdrawCashDone: false
			});
		}, function() {
			//回滚回去
			db.update('storeOrder', {withdrawCashId: ''}).then(function() {});
			//连接到公共数据库失败
			deferred.reject('-0127');
		}).then(function() {
			deferred.resolve(withdrawCashId);
		}, function() {
			//回滚回去
			db.update('storeOrder', {withdrawCashId: ''}).then(function() {});
			//向公共数据库的提现列表插入提现记录失败
			deferred.reject('-0128');
		});
	}, function() {
		//生成随机字符串失败
		deferred.reject('-0069');
	});
	return deferred.promise;
}

let getUserId = function(_3rdSession) {
	let deferred = Q.defer();
	redis.get(_3rdSession).then(function(data) {
		console.log('用户数据', data);
		data = JSON.parse(data);
		deferred.resolve(data.openId);
	}, function(err) {
		console.log(err);
		deferred.reject();
	});
	return deferred.promise;
}

module.exports = {
	index: index
}